const envPrefix = 'VUE_APP_'

const ignoreEnv = ['OFFLINE', 'VUEX_LOG', 'BUNDLE_ANALYZER', 'DOWNLOAD_BROWSER'].map(value => envPrefix + value)

const stringToBoolean = str => {
  if (['true', 'Y'].includes(str)) {
    return true
  } else if (['false', 'N'].includes(str)) {
    return false
  } else {
    return str
  }
}

const camelize = (str, separator = '-') => {
  if (!str) {
    return str
  }
  return str.replace(new RegExp(`${separator}(\\w)`, 'g'), (_, c) => (c ? c.toUpperCase() : ''))
}

const genConfig = () => {
  const env = process.env
  const data = {}
  const keys = Object.keys(env).filter(key => key.startsWith(envPrefix))
  if (keys.length) {
    keys.forEach(key => {
      if (!ignoreEnv.includes(key)) {
        const prop = camelize(key.replace(`${envPrefix}`, '').toLowerCase(), '_')
        data[prop] = stringToBoolean(env[key])
      }
    })
  }
  return data
}

module.exports = {
  stringToBoolean,
  camelize,
  genConfig,
  envPrefix,
  ignoreEnv
}
